package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcelBuilder;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.mcc.permit.client.annotation.FilterPermitData;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.work.masterwork.MasterWorkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.financework.FinanceWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryExportBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：工单查询
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@RequestMapping("/all/work")
@Slf4j
public class WorkListController extends WorkListTabBaseController {

    @Autowired
    FinanceWorkService financeWorkService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    MasterWorkBService masterWorkBService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    ZsOrderWorkQueryExportBService zsOrderWorkQueryExportBService;

    /**
     * 工单列表
     */
    @RequiresPermissions("/all/work/list.action")
    @RequestMapping(value = "/list")
    public ModelAndView list(ModelAndView mv) {
        mv.setViewName("work/list/all/list");
        // 下单日期
        mv.addObject("receiveTimeStart", DateUtil.getMonthFirstDay(DateUtil.getNow()));
        mv.addObject("receiveTimeEnd", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));

        // tab
        List<KVDict> tabList = Lists.newArrayList();
        List<Integer> additionTabList = Lists.newArrayList();

        //精确查询
        if (StaffAdminService.isPermitted("/work/list/precision/query.action")) {
            Integer tabValue = -1;
            tabList.add(KVDict.builder().value(GlobalConsts.NONE).text("精确查询").type(tabValue).ext1("2").build());
            additionTabList.add(tabValue);
        }

        // 批量查询
        if (StaffAdminService.isPermitted("/all/work/batch/query/list.action")) {
            Integer tabValue = OrderConsts.QUERY_TAB_WAIT_CONFIRM;
            tabList.add(KVDict.builder().value(GlobalConsts.NONE).text("批量查询").type(tabValue).ext1("2").build());
            additionTabList.add(tabValue);
        }

        mv.addObject("tabList", tabList);
        mv.addObject("additionTabList", additionTabList);

        super.setDayLimit(mv);
        super.setDefaultModelAndView(mv);

        return mv;
    }

    /**
     * 工单列表 ajax
     */
    @RequiresPermissions("/all/work/list.action")
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody OrderWorkQuery query) {
        // 处理查询条件
        processSearchQuery(query);

        List<ZsOrderWorkVO> voList = zsOrderWorkQueryBService.listPageOrderWorkByQuery(query);

        LayuiTableDO<ZsOrderWorkVO> data = new LayuiTableDO<>();
        data.setCount(query.getTotalCount());
        data.setData(voList);
        return ResultDTO.success(data);
    }

    /**
     * 工单,单条 ajax
     */
    @RequiresPermissions("/all/work/list.action")
    @GetMapping(value = "/ajax/row")
    @ResponseBody
    public ResultDTO ajaxRow(@Valid OrderWorkQuery query) {
        // 处理查询条件
        processSearchQuery(query);

        List<ZsOrderWorkVO> voList = zsOrderWorkQueryBService.listPageOrderWorkByQueryNoRecord(query);
        if (CollectionUtils.isEmpty(voList)) {
            return null;
        }

        return ResultDTO.success(voList.get(0));
    }

    /**
     * 工单列表导出 ajax
     */
    @RequestMapping(value = "/list/export")
    @ResponseBody
    public void ajaxListExport(OrderWorkQuery query, HttpServletResponse response) throws Exception {

        query.setPageSize(10000);

        // 处理查询条件
        processSearchQuery(query);

        // 处理导出数量
        processExportPermitQuery(query);

        // 导出
        ExportExcelBuilder excelBuilder = zsOrderWorkQueryExportBService.exportListOrderWorkByQuery(query, false);
        excelBuilder.exportExcel(response, "工单管理");
    }

    /**
     * 工单列表导出 ajax
     */
    @PostMapping("/list/export/async")
    @FilterPermitData
    @ResponseBody
    public ResultDTO ajaxListExportAsync(@RequestBody OrderWorkQuery query) {

        query.setPageSize(10000);

        // 处理查询条件
        processSearchQuery(query);

        // 处理导出数量
        processExportPermitQuery(query);

        // 导出
        try {
            zsOrderWorkQueryExportBService.buildExportTask(query, true);
        } catch (OmsBaseException e) {
            return ResultDTO.fail(e.getMessage());
        }
        return ResultDTO.success();
    }

    /**
     * 处理查询条件
     *
     * @param query
     */
    private void processSearchQuery(OrderWorkQuery query) {
        // 脱敏
        // query.setIsSensitiveAddr(!StaffAdminService.isPermitted("/all/work/list/address.action"));
        query.setIsSensitiveAddr(true);
        query.setIsSensitiveTel(true);

        // 数据权限
        query.setPermit(GlobalConsts.YES);
        query.setQueryWarning(GlobalConsts.YES);
        // 查询手机号对应的用户
        query.setQueryConcatPhoneUsers(true);

        // 精准查询特殊处理
        if (Objects.equals(-1, query.getTabType())) {
            // 精准，不需要权限，但是 手机号码和工单号必有一个 cryptoPhone
            if (StringUtils.isNotBlank(query.getConcatPhone()) || NumberUtil.isNotNullOrZero(query.getCode())) {
                query.setPermit(GlobalConsts.NO);
            }
        }

    }
}